package cn.com.hhrcw.service.impl;

import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.service.IFileService;
import cn.com.hhrcw.service.TopJobClientService;
import cn.com.hhrcw.service.TopJobEnFileConvert;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.properties.FileUploadProperties;
import org.jeecg.common.system.vo.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
@Slf4j
@Service
public class TopJobClientServiceImpl implements TopJobClientService {
    @Autowired
    private FileUploadProperties properties;
    @Autowired
    private TopJobEnFileConvert topJobEnFileConvert;
    @Autowired
    private IFileService fileService;
    @Value(value = "${jeecg.path.upload}")
    private String uploadPath;
    @SneakyThrows
    @Override
    public Object uploadToLocal(byte[] bytes, String biz, String sourceName, Integer fileType, boolean isFileId) {
        Object value = null;
        fileType = fileType == null ? -1 : fileType;
        InputStream copyStream = IoUtil.toStream(bytes);
        //对文件进行md5签名
        String sign = SecureUtil.md5(copyStream);
        String ext = FileUtil.extName(sourceName);
        int type = -10;
        if (fileType == type) {
            sign = sourceName.replace("." + ext, "");
        }
        //后缀
        //判断文件是否已经上传过了
        String path = this.uploadToLocal(bytes, biz, StrUtil.format("{}.{}", sign, ext));
        Assert.notBlank(path, "文件保存失败");
        String url = "";
        String id = IdUtil.getSnowflake(4, 4).nextIdStr();
        boolean contains = StrUtil.contains(biz, "public/");
        if (contains) {
            url = properties.getPublicCdn() + "/" + biz.replace("public/", "") + "/" + FileUtil.getName(path);
        } else {
            url = properties.getPrivateCdn() + "/" + id;
        }
        //保存文件到数据库
        FileInfo fileInfo = new FileInfo();
        //不保存到file表
        type = -11;
        if (fileType != type && isFileId) {
            fileInfo.setId(id).setFileName(sign).setUrl(url).setFilePath(path).setFileRealName(sourceName).setFileSize(Convert.toLong(bytes.length)).setFileType(fileType);
            this.saveFile(fileInfo);
        }
        if (isFileId) {
            Map<String, String> map = Maps.newHashMap();
            map.put("name", sourceName);
            map.put("fileId", fileInfo.getId());
            map.put("url", url);
            value = map;
        } else {
            value = path;
        }
        IoUtil.close(copyStream);
        return value;
    }
    public String uploadToLocal(byte[] bytes, String biz, String sourceName) throws IOException {
        String ctxPath = uploadPath;
        File file = new File(ctxPath + File.separator + biz + File.separator);
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
        String savePath = file.getPath() + File.separator + sourceName;
        File saveFile = new File(savePath);
        FileCopyUtils.copy(bytes, saveFile);
        return saveFile.getAbsolutePath();
    }
    public FileInfo saveFile(FileInfo fileInfo) {
        String userId="";
        SysUser user = (SysUser) SubjectUtils.getSubject();
        userId=user.getId();
        cn.com.hhrcw.entity.File file = topJobEnFileConvert.toEntity(fileInfo);
        String realName = fileInfo.getFileRealName();
        int inx = realName.lastIndexOf(".");
        String name = realName.substring(0, inx);
        String ext = realName.substring(inx + 1);
        file.setId(fileInfo.getId());
        file.setFileRealName(name);
        file.setFileLastName(ext);
        file.setCreateTime(DateUtil.date());
        file.setDelFlag(false);
        file.setCreateBy(userId);
        fileService.saveOrUpdate(file);
        return fileInfo;
    }


}
